package com.zlp.controller;

import com.zlp.common.utils.FileUtil;
import com.zlp.dto.CacheUpload;
import com.zlp.dto.UploadResp;
import com.zlp.dto.UploadVO;
import com.zlp.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;


/**
 * @version V1.0
 * @description: 测试OSS功能
 * @author: ZouLiPing
 * @contact: 请关注微信公众号“给自己一个smile”里面有详细电商项目文档,weixin:zlp865391093
 * @date: 2019年3月29日15:18:33
 */
@Slf4j
@RestController
@RequestMapping("/file")
@Api(value = "file", tags = "文件模块")
public class FileController {

    @Autowired
    private FileService fileService;

    //仓库中的某个文件夹
    public static final String FILE_HOST = "test";


    /**
     * 测试上传文件到阿里云OSS存储(不支持上传文件，推荐作为图床使用)
     *
     * @return
     */
    @PostMapping("/testUpload")
    @ApiOperation(value = "测试上传文件")
    public String testUpload() {
        String picPath = "D:\\file\\test\\nirsit.txt";
        MultipartFile file = FileUtil.getMulFileByPath(picPath);
        String url = fileService.uploadFile(FILE_HOST, file);
        return url;
    }

    /**
     * 文件上传
     */
    @PostMapping("/uploadFile")
    @ApiOperation(value = "文件上传")
    public String uploadFile(HttpServletRequest request,
                             @RequestParam("file") MultipartFile file,
                             @RequestParam("personId") String personId,
                             @RequestParam("reportNo") String reportNo,
                             @RequestParam("category") Integer category
    ) {


        log.info("uploadFile.req personId={},reportNo={},category={}", personId, reportNo, category);
        log.info("token====>{}", request.getHeader("Authorization"));
        String url = fileService.uploadFile(FILE_HOST, file);
        return url;
    }


    /**
     * 下载文件
     */
    @GetMapping("/downloadFile")
    @ApiOperation(value = "下载文件")
    public ResponseEntity<byte[]> downloadFile(@RequestParam("fileName") String fileName) {

        log.info("downloadFile.req fileName={}", fileName);

        return fileService.downloadObject(fileName);

    }


    /**
     * 文件（二进制数据）下载
     *
     * @param fileType 文件类型
     * @return
     */
    @GetMapping("/downloadLocalFile")
    public ResponseEntity<byte[]> downloadLocalFile(String fileType) {

        log.info("参数fileType: " + fileType);
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        try {
            in = new FileInputStream(new File("D:\\file\\report\\2021-07\\B01072120252275\\源数据 (6).zip"));
            int available = in.available();
            log.info("文件大小={}", available);
            byte[] bytes = new byte[available];
            String imageName = "报告.zip";
            imageName = new String(imageName.getBytes(), "iso-8859-1");
            in.read(bytes);
            headers.setContentType(MediaType.ALL.APPLICATION_OCTET_STREAM);
            headers.add("Content-Disposition", "attachment;filename=" + imageName);
            entity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return entity;
    }


    /**
     * 文件（二进制数据）下载
     *
     * @param file 文件类型
     * @return
     */
    @PostMapping("/uploadStaticFile")
    public String uploadStaticFile(@RequestParam("file") MultipartFile file,
                                   @RequestParam("filename") String filename
    ) {
        log.info("uploadStaticFile.req filename={},path={}", filename);

        String url = fileService.uploadFile(FILE_HOST, file);
        return url;
    }


    @PostMapping("/uploadFileProgress")
    @ApiOperation(value = "文件上传带进度条")
    public UploadResp uploadFileProgress(@RequestParam("file") MultipartFile file,
                                         @RequestParam("uploadNo") String uploadNo
    ) {

        long fileSize = (file.getSize() / 1024 * 100) / 100;
        UploadResp uploadResp = fileService.uploadFileProgress(file, FILE_HOST, fileSize, uploadNo);
        return uploadResp;
    }

    /**
     * 获取进度条
     */
    @GetMapping(value = "/getProgressBar")
    @ApiOperation(value = "获取进度条")
    public UploadVO getProgressBar(@RequestParam("uploadNo") String uploadNo) {

        UploadVO uploadVO;
        for (; ; ) {
            uploadVO = CacheUpload.getProgressBar(uploadNo);
            if (Objects.nonNull(uploadVO)) {
                log.info("getProgressBar.resp uploadVO={}", uploadVO.toString());
                if (uploadVO.getProgressBar().compareTo(new BigDecimal(100.00)) == 0) {
                    break;
                }
            }
        }
        CacheUpload.removeProgressBar(uploadNo);

        return uploadVO;
    }

    /**
     * 列出某个文件夹下的所有文件
     */
    @GetMapping("/testListFile")
    @ApiOperation(value = "列出某个文件夹下的所有文件")
    public List<String> testListFile(@RequestParam("filePath") String filePath) {

        return fileService.listFile(filePath);
    }

    /**
     * 删除文件
     */
    @GetMapping("/delFile")
    @ApiOperation(value = "删除文件")
    public String delFile(@RequestParam("filePath") String delFileUrl) {
        fileService.delFile(delFileUrl);
        return "success";
    }

}
